var http = require('http');
var querystring = require('querystring');

var port = 80;
var ip = '127.0.0.1';
var date = new Date();
var server = http.createServer(function (request, response) {
	response.writeHead(200, {'Content-Type': 'text/html','Server':'tjg_private'});
	response.statusMessage = "hehehe";
	//response.statusCode = 404;
	//response.setHeader('Content-Type','text/html');
	//response.setHeader('Server','tjg_private');
	var url = require('url').parse(request.url,true);
	//console.log(url)
	var fs = require('fs'); // 载入fs模块
	var tjg = '404';
	var suffix= request.url.substr(request.url.lastIndexOf(".")+1);
	//console.log(suffix)
	var exts = {
		'html':'text/html',
		'css':'text/css',
		'js':'application/x-javascript',
		'jpg':'image/jpeg',
		'png':'image/png',
	}
	response.writeHead(200, {'Content-Type': exts[suffix]});
	if (exts[suffix]==null) {
		response.writeHead(200, {'Content-Type': 'text/plain'});
	}
	var MyPage = '我的主页';
	if (request.url=='/index.html') {
		try{
			var item = fs.readFileSync("data.json",'utf8');
			item = JSON.parse(item)
			var s = ''
			for(var i=0;i<item.length;i++){
				s+= '<div class="item">' 
				s+= '<h6>'+item[i].author+'<span>'+item[i].time+'</span></h6>'
				s+= '<p><span id="content">'+item[i].message+'</span>'+'<a id="del" href="/delmessage?id='+i+'">删除</a>'+'</p>'
				s+= '</div>'
			}
			var tjg = fs.readFileSync("."+request.url,'utf8');
			tjg = tjg.replace(/%title/g,MyPage)
			tjg = tjg.replace(/%main/g,s);
		}catch(e){}
		response.write(tjg);
		response.end();
	}else if (request.url=='/form.html') {
		var tjg = fs.readFileSync("."+request.url,'utf8');
		response.write(tjg);
		response.end();
	}else if (url.pathname=='/addmessage') {
		/*item = JSON.parse(fs.readFileSync("data.json",'utf8'));
		item.push({
			"author":url.query.author,
			"time":date,
			"message":url.query.message
		})
		item = JSON.stringify(item);
		fs.writeFile('data.json',item);
		response.writeHead(302,{
			Location:'/index.html'
		})*/
		// 定义了一个post变量，用于暂存请求体的信息
	    var post = '';
	    // 通过req的data事件监听函数，每当接受到请求体的数据，就累加到post变量中
	    request.on('data', function(chunk){    
	        post += chunk;
	    });
	    // 在end事件触发后，通过querystring.parse将post解析为真正的POST请求格式，然后向客户端返回。
	    
	    request.on('end', function(){    
	        post = querystring.parse(post);
	        item = JSON.parse(fs.readFileSync("data.json",'utf8'));
	        item.push({
				"author":post.author,
				"time":date,
				"message":post.message
			})
			item = JSON.stringify(item);
			fs.writeFile('data.json',item);
			response.writeHead(302,{
				Location:'/index.html'
			})
		response.write(tjg);
		response.end();
	    });
	}else if (url.pathname=='/delmessage') {
		var x= url.query.id;
		item = JSON.parse(fs.readFileSync("data.json",'utf8'));
		item.splice(x,1);
		item = JSON.stringify(item);
		fs.writeFile('data.json',item);
		response.writeHead(302,{
			Location:'/index.html'
		})
		response.write(tjg);
		response.end();
	}else{
		try{
		var tjg = fs.readFileSync("."+request.url,'utf8');
			}catch(e){}
		response.write(tjg);
		response.end();
	}
}).listen(80);//监听80窗口

// 终端打印如下信息
console.log('Server running at http://%s:%s/',ip,port);
/*function delay(delaytime){
	var sleep = date.getTime()
	while(new Date() >= sleep+delaytime){}
}*/